/**
 * @filename:Contract3Controller 2024-01-01 00:00:00
 * @project com/lwl/blue  V1.0
 * Copyright(c) 2024 <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a> Co. Ltd.
 * All right reserved.
 */
package com.lwl.blue.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lwl.blue.commont.base.*;
import com.lwl.blue.entity.Contract3;
import com.lwl.blue.entity.ContractDetail3;
import com.lwl.blue.service.Contract3Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>自定义方法写在这里</p>
 *
 * <p>说明： 采购合同主表API接口层</P>
 *
 * @version: V1.0
 * @author: <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a>
 */
@RestController
@RequestMapping("/purchaseContract")
@Slf4j
public class Contract3Controller extends BaseController {
    
    @Autowired
    private Contract3Service contract3Service;

    /**
     * 分页查询采购合同
     * @param pageParam 分页参数
     * @return 分页结果
     */
    @PostMapping("/pages")
    public PageResult<Contract3> getPages(@RequestBody PageParam<Contract3> pageParam) {
        try {
            JsonResult<Page<Contract3>> result = contract3Service.pages(pageParam);
            if (result.isSuccess()) {
                PageResult<Contract3> pageResult = new PageResult<>();
                pageResult.success(result.getData().getTotal(), result.getData().getRecords());
                return pageResult;
            } else {
                PageResult<Contract3> pageResult = new PageResult<>();
                pageResult.error(result.getMessage());
                return pageResult;
            }
        } catch (Exception e) {
            log.error("分页查询采购合同失败", e);
            PageResult<Contract3> pageResult = new PageResult<>();
            pageResult.error("分页查询采购合同失败：" + e.getMessage());
            return pageResult;
        }
    }

    /**
     * 根据合同内码查询合同详情（包含供应商信息）
     * @param contractInnerId 合同内码
     * @return 合同详情
     */
    @GetMapping("/detail/{contractInnerId}")
    public JsonResult<Contract3> getContractDetail(@PathVariable String contractInnerId) {
        return contract3Service.getContractWithSupplier(contractInnerId);
    }

    /**
     * 根据关联订单号查询合同列表
     * @param relatedOrderNo 关联订单号
     * @return 合同列表
     */
    @GetMapping("/byOrder/{relatedOrderNo}")
    public JsonResult<List<Contract3>> getContractsByOrder(@PathVariable String relatedOrderNo) {
        return contract3Service.getContractsByRelatedOrderNo(relatedOrderNo);
    }

    /**
     * 根据合同号模糊查询合同
     * @param contractNo 合同号
     * @return 合同列表
     */
    @GetMapping("/search/{contractNo}")
    public JsonResult<List<Contract3>> searchContracts(@PathVariable String contractNo) {
        return contract3Service.getContractsByContractNoLike(contractNo);
    }

    /**
     * 统计执行中合同的总金额
     * @param contractStatus 合同状态
     * @return 总金额
     */
    @GetMapping("/totalAmount/{contractStatus}")
    public JsonResult<BigDecimal> getTotalAmount(@PathVariable Integer contractStatus) {
        return contract3Service.getTotalAmountByStatus(contractStatus);
    }

    /**
     * 根据合同内码查询合同明细列表
     * @param contractInnerId 合同内码
     * @return 合同明细列表
     */
    @GetMapping("/details/{contractInnerId}")
    public JsonResult<List<ContractDetail3>> getContractDetails(@PathVariable String contractInnerId) {
        return contract3Service.getContractDetails(contractInnerId);
    }

    /**
     * 根据合同内码查询合同明细（包含产品信息）
     * @param contractInnerId 合同内码
     * @return 合同明细列表
     */
    @GetMapping("/detailsWithItem/{contractInnerId}")
    public JsonResult<List<ContractDetail3>> getContractDetailsWithItem(@PathVariable String contractInnerId) {
        return contract3Service.getContractDetailsWithItem(contractInnerId);
    }

    /**
     * 生成采购合同（从订单数据生成）
     * @param relatedOrderNo 关联订单号
     * @return 生成的合同信息
     */
    @PostMapping("/generate/{relatedOrderNo}")
    public JsonResult<Contract3> generateContract(@PathVariable String relatedOrderNo) {
        return contract3Service.generateContractFromOrder(relatedOrderNo);
    }

    /**
     * 更新合同状态
     * @param contractInnerId 合同内码
     * @param contractStatus 新状态
     * @return 更新结果
     */
    @PutMapping("/status/{contractInnerId}/{contractStatus}")
    public JsonResult<Boolean> updateContractStatus(@PathVariable String contractInnerId, @PathVariable Integer contractStatus) {
        return contract3Service.updateContractStatus(contractInnerId, contractStatus);
    }

    /**
     * 导出合同模板
     * @param contractInnerId 合同内码
     * @param response HTTP响应
     */
    @GetMapping("/export/{contractInnerId}")
    public void exportContractTemplate(@PathVariable String contractInnerId, HttpServletResponse response) {
        contract3Service.exportContractTemplate(contractInnerId, response);
    }

    /**
     * 新增采购合同
     * @param contract 合同信息
     * @return 新增结果
     */
    @PostMapping("/add")
    public JsonResult<Boolean> addContract(@Valid @RequestBody Contract3 contract) {
        try {
            boolean result = contract3Service.save(contract);
            return new JsonResult<Boolean>().success(result);
        } catch (Exception e) {
            log.error("新增采购合同失败", e);
            return new JsonResult<Boolean>().error("新增采购合同失败：" + e.getMessage());
        }
    }

    /**
     * 修改采购合同
     * @param contract 合同信息
     * @return 修改结果
     */
    @PutMapping("/update")
    public JsonResult<Boolean> updateContract(@Valid @RequestBody Contract3 contract) {
        try {
            boolean result = contract3Service.updateById(contract);
            return new JsonResult<Boolean>().success(result);
        } catch (Exception e) {
            log.error("修改采购合同失败", e);
            return new JsonResult<Boolean>().error("修改采购合同失败：" + e.getMessage());
        }
    }

    /**
     * 删除采购合同
     * @param contractInnerId 合同内码
     * @return 删除结果
     */
    @DeleteMapping("/delete/{contractInnerId}")
    public JsonResult<Boolean> deleteContract(@PathVariable String contractInnerId) {
        try {
            boolean result = contract3Service.removeById(contractInnerId);
            return new JsonResult<Boolean>().success(result);
        } catch (Exception e) {
            log.error("删除采购合同失败", e);
            return new JsonResult<Boolean>().error("删除采购合同失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询采购合同
     * @param contractInnerId 合同内码
     * @return 合同信息
     */
    @GetMapping("/{contractInnerId}")
    public JsonResult<Contract3> getContractById(@PathVariable String contractInnerId) {
        try {
            Contract3 contract = contract3Service.getById(contractInnerId);
            if (contract == null) {
                return new JsonResult<Contract3>().error("合同不存在");
            }
            return new JsonResult<Contract3>().success(contract);
        } catch (Exception e) {
            log.error("查询采购合同失败", e);
            return new JsonResult<Contract3>().error("查询采购合同失败：" + e.getMessage());
        }
    }
}